﻿
namespace Huirui.Cavan.Presentation.Seedwork
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics.Contracts;
    using System.Linq;
    using System.Web.Mvc;
    using System.Web.Routing;
    using Huirui.Cavan.Core.Persistent;
    using Huirui.Cavan.Application.Seedwork;
    using Huirui.Cavan.Core.Message;
    using System.IO;

    public abstract class EntityController<T, TSearch, TModel, TAppService>
        : EntityController<T, int, TSearch, TModel, TAppService>
        where T : class, IPersistentObjectWithTypedId<int>
        where TSearch : class,ISearch<int>, new()
        where TModel : class, IEditModel<T, int, TSearch>
        where TAppService : class, IEntityAppService<T, int, TSearch>
    {
    }

    public abstract class EntityController<T, TID, TSearch, TModel, TAppService>
        : ReadController<T, TID, TSearch, TModel, TAppService>
        where T : class, IPersistentObjectWithTypedId<TID>
        where TSearch : class,ISearch<TID>, new()
        where TModel : class, IEditModel<T, TID, TSearch>
        where TAppService : class, IEntityAppService<T, TID, TSearch>
    {
        #region protected OnBind
        protected virtual bool OnBindModel()
        {
            return BindModel(Model.Item);
        }
        #endregion protected OnBind

        #region render partialview
        protected string RenderPartialViewToString()
        {
            return RenderPartialViewToString(null, null);
        }

        protected string RenderPartialViewToString(string viewName)
        {
            return RenderPartialViewToString(viewName, null);
        }

        protected string RenderPartialViewToString(object model)
        {
            return RenderPartialViewToString(null, model);
        }

        protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }
        #endregion
    }
}